package com.example.study.page.fragment

import android.annotation.SuppressLint
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.Bundle
import android.os.IBinder
import android.os.RemoteException
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.example.study.ipc.Book
import com.example.study.ipc.BookManagerService
import com.example.study.ipc.BookManagerStub
import com.example.study.ipc.IBookManager
import com.example.study.databinding.FragmentIPCBinding

class IPCFragment : Fragment() {
    private var bookManager: IBookManager? = null
    private lateinit var binding: FragmentIPCBinding
    private var isConnection = false

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = FragmentIPCBinding.inflate(layoutInflater, container, false)
        return binding.root
    }

    @SuppressLint("SetTextI18n")
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding.button.setOnClickListener {
            if (!isConnection) {
                attemptToBindService()
                return@setOnClickListener
            }
            if (bookManager == null) return@setOnClickListener
            try {
                val book = Book(101, "编码")
                bookManager?.addBook(book)
                val books = bookManager?.getBooks()
                binding.text.text = "Current Books: " + books.toString()
            } catch (e: RemoteException) {
                e.printStackTrace()
            }
        }
    }


    private fun attemptToBindService() {
        val intent = Intent(context, BookManagerService::class.java)
        intent.action = "com.example.study.aidl"
        activity?.bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE)
    }

    private val serviceConnection = object : ServiceConnection {
        @SuppressLint("SetTextI18n")
        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            isConnection = true
            bookManager = BookManagerStub.asInterface(service)
            try {
                val books = bookManager?.getBooks()
                binding.text.text = "Current Books:" + books.toString()
            } catch (e: RemoteException) {
                e.printStackTrace()
            }
        }

        override fun onServiceDisconnected(name: ComponentName?) {
            isConnection = false
        }

    }

    override fun onStart() {
        super.onStart()
        if (!isConnection) attemptToBindService()
    }

    override fun onStop() {
        super.onStop()
        if (isConnection) activity?.unbindService(serviceConnection)
    }
}